package com.lidd.selffood.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author lixunhuan
 * @since 2021-03-06
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.lidd.selffood.db", sqlSessionFactoryRef = "rechargeSqlSessionFactory")
public class DBConfig {

    @Bean
    @ConfigurationProperties(prefix = "datasource.selfstudy")
    public DataSource rechargeDataSource() {
        return new HikariDataSource();
    }

    @Bean
    public SqlSessionFactory rechargeSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(rechargeDataSource());
        bean.setTypeAliasesPackage("com.lidd.selffood.db.bean");
        bean.getObject().getConfiguration().addMappers("com.lidd.selffood.db.mapper");
        org.apache.ibatis.session.Configuration configuration = bean.getObject().getConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }

    @Bean(name = "rechargeTransactionManager")
    public DataSourceTransactionManager rechargeTransactionManager()  {
        return new DataSourceTransactionManager(rechargeDataSource());
    }
}
